#!/bin/bash
#
# This script initializes three Fabric CA servers, each for an organization.

source ./utils.sh

# Prints the "directory existing" hint.
printDirectoryExistingHint() {
    printf "The server directory for '%s' seems to already exists. Delete it first if you'd like to recreate this server.\n" $ORG_NAME
}

# Init a CA server of the organization specified by $ORG_NAME.
initServer() {
    setServerEnvVars

    if [ -d "./server/${ORG_NAME}" ]; then
        printDirectoryExistingHint
        return 2
    fi

    printf "Initializing CA server for '%s'..." ${ORG_NAME}

    mkdir -p "${WORKING_DIR}/server/${ORG_NAME}"
    cd "${WORKING_DIR}/server/${ORG_NAME}"
    fabric-ca-server init -b admin:adminpw >/dev/null 2>&1

    if [ $? -ne 0 ]; then
        printf "\rError initializing CA server for '%s'.\n" ${ORG_NAME}
        return 3
    else
        printf "\rDone initializing CA server for '%s'.\n" ${ORG_NAME}
    fi
}

# Main script
checkBinAvailability || {
    printf "Error: Fabric CA binaries not available.\n"
    exit 1
}

WORKING_DIR=${PWD}

IS_ALL_SUCCESS=true
for ORG_NAME in "org1" "org2" "ordererOrg"; do
    initServer || IS_ALL_SUCCESS=false
done

if [ ${IS_ALL_SUCCESS} == false ]; then
    exit 2
fi
